﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using X.PagedList;
using XbsWebAPI.Application.Detaileds.Dto;
using XbsWebAPI.Application.QueryModel;
using XbsWebAPI.Core.Repositories.Detaileds;
using XbsWebAPI.EntityFrameworkCore.Entities.Detailed;

namespace XbsWebAPI.Application.Detaileds
{
    public class DetailedAppService : IDetailedAppService
    {
        private readonly IDetailedRepository _detailRepository;
        private readonly IMapper _imapper;
        public DetailedAppService(IDetailedRepository detailRepository, IMapper imapper)
        {
            _detailRepository = detailRepository;
            _imapper = imapper;
        }
        /// <summary>
        /// 新增收入明细
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Task<ResultDto<CreateDetailedDto>> AddDetail(CreateDetailedDto model)
        {
            var result = new ResultDto<CreateDetailedDto>();
            var entity=_imapper.Map<Detailed>(model);
            var res = _detailRepository.CreateAsync(entity);
            if (res.Result==null)
            {
                result.Code = -1;
                result.Message = "添加失败";
            }
            else
            {
                result.Code = 0;
                result.Message = "添加成功";
            }
            return Task.FromResult(result);
        }
        /// <summary>
        /// 分页查询/条件查询
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResultDto<PageListDto<CreateDetailedDto>> FindDetailPagedList(QueryDetailed model)
        {
            var result=new ResultDto<PageListDto<CreateDetailedDto>>();
            //全查收支明细表
            var data=_detailRepository.AsQueryable();
            //判断条件是否为空
            if (!string.IsNullOrWhiteSpace(model.OrderNumber))
            {
                data = data.Where(a => a.OrderNumber.Contains(model.OrderNumber));
            }
            if (!string.IsNullOrWhiteSpace(model.WxName))
            {
                data = data.Where(a => a.WxName.Contains(model.WxName));
            }
            data = data.OrderByDescending(a => a.CreationDate);
            var PageList = data.ToPagedList(model.PageNumber ?? 1,model.PageSize??10);
            var pagelist = new PageListDto<CreateDetailedDto>();
            pagelist.PageNumber = PageList.PageNumber;
            pagelist.PageSize = PageList.PageSize;
            pagelist.HasNextPage = PageList.HasNextPage;
            pagelist.TotalCount = PageList.TotalItemCount;
            var dto = PageList.Select(a => _imapper.Map<CreateDetailedDto>(a)).ToList();
            pagelist.Dtos = dto;
            result.Code = 0;
            result.Message = "查询成功";
            result.Result = pagelist;
            return result;
        }
    }
}
